use crate::config;
use deadpool_redis::{ConnectionAddr, ConnectionInfo, ProtocolVersion, RedisConnectionInfo, Runtime};

/// 加载RedisPool配置信息
///
/// # 返回值
/// - `anyhow::Result<deadpool_redis::Config>`
/// - `deadpool_redis::Config` - redis pool的Config配置信息
pub fn load() -> anyhow::Result<deadpool_redis::Config> {
    let redis_config = config::get().redis()?;
    let redis_connection_info = RedisConnectionInfo {
        db: redis_config.db(),
        username: Some(String::from(redis_config.user())),
        password: Some(String::from(redis_config.password())),
        protocol: ProtocolVersion::default(),
    };
    let connection_info = ConnectionInfo {
        addr: ConnectionAddr::Tcp(String::from(redis_config.host()), redis_config.port()),
        redis: redis_connection_info,
    };

    let config = deadpool_redis::Config::from_connection_info(connection_info);

    Ok(config)
}
/// 获取redis链接
///
/// # 返回值
/// - `anyhow::Result<deadpool_redis::Connection>`
/// - `deadpool_redis::Connection` - redis数据链接
pub async fn get() -> anyhow::Result<deadpool_redis::Connection> {
    let cfg = load()?;
    let pool = cfg.create_pool(Some(Runtime::Tokio1))?;
    let conn = pool.get().await?;
    Ok(conn)
}

/// 日志redis信息
pub async fn log_redis_version() -> anyhow::Result<()> {
    let mut conn = get().await?;
    let info: String = deadpool_redis::redis::cmd("INFO").arg(&["server"]).query_async(&mut conn).await?;
    tracing::info!("Redis版本信息: {}", info);
    Ok(())
}